//
//  MGFile.m
//  iFlyQDMG
//
//  Created by ifly on 3/9/18.
//  Copyright © 2018年 Meiyang. All rights reserved.
//

#import "MGFile.h"

@implementation MGFile

+ (instancetype)shared{
    
    static MGFile *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[MGFile alloc] init];
    });
    return manager;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self jcCreateDirectory];
    }
    return self;
}

//  总的储存路径 根据用户名 进行
- (NSString *)cacheDirectory{
    
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cacheDirectory = [paths objectAtIndex:0];
    cacheDirectory = [cacheDirectory stringByAppendingPathComponent:@"ZYCaches"];
    
    return cacheDirectory;
}

/// pdf储存路径
- (NSString *)jcCachePath{
    return [[self cacheDirectory] stringByAppendingPathComponent:@"ztbCaches"];
}
/// 备份路径
- (NSString *)jcBackupCachesPath{
    return [[self cacheDirectory] stringByAppendingPathComponent:@"ztbBackupCaches"];
}

/// 创建储存文件夹 基本缓存文件夹和备份专用文件夹
- (void) jcCreateDirectory{
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:[self cacheDirectory]]) {
        NSError *err;
        [fileManager createDirectoryAtPath:[self cacheDirectory] withIntermediateDirectories:YES attributes:nil error:&err];
    }
//  储存文件夹路径
    if (![fileManager fileExistsAtPath:[self jcCachePath]]) {
        NSError *err;
        [fileManager createDirectoryAtPath:[self jcCachePath] withIntermediateDirectories:YES attributes:nil error:&err];
    }
    
//  备份储存文件夹路径
    if (![fileManager fileExistsAtPath:[self jcBackupCachesPath]]) {
        NSError *err;
        [fileManager createDirectoryAtPath:[self jcBackupCachesPath] withIntermediateDirectories:YES attributes:nil error:&err];
    }
}

/// 将下载的pdf 文件进行备份
- (BOOL)jcCachesOfBackup{
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *err;
//   添加
    NSString *jcBacjuppath = [[self jcBackupCachesPath] stringByAppendingPathComponent:@"ztbCaches"];
    
    if ([fileManager fileExistsAtPath:jcBacjuppath]) {
        [fileManager removeItemAtPath:jcBacjuppath error:nil];
    }
    BOOL us = [fileManager copyItemAtPath:[self jcCachePath] toPath:jcBacjuppath error:&err];
    return us;
}

/// 使用该备份数据
- (BOOL) jcRestoreCaches{
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *err;
    //   添加
    NSString *jcBacjuppath = [[self jcBackupCachesPath] stringByAppendingPathComponent:@"ztbCaches"];
    
    if ([fileManager fileExistsAtPath:[self jcCachePath]]) {
        [fileManager removeItemAtPath:[self jcCachePath] error:nil];
    }
    BOOL us = [fileManager copyItemAtPath:jcBacjuppath toPath:[self jcCachePath] error:&err];
    NSLog(@"-------%@",err);
    return us;
}
// 获取备份数据内容
- (NSDictionary *)jcGetBackup{
    
    NSMutableDictionary *jcDic = [NSMutableDictionary dictionary];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *jcBacjuppath = [[self jcBackupCachesPath] stringByAppendingPathComponent:@"ztbCaches"];
    
    if (![fileManager fileExistsAtPath:jcBacjuppath]) {
        [jcDic setObject:@"0" forKey:@"isBackup"];
    }
    float fileLength = [self jcGetCachesWithPath:jcBacjuppath];
    
    NSError *error;
    NSDictionary *attributes = [fileManager attributesOfItemAtPath:jcBacjuppath error:&error];
    if (!error) {
        [jcDic setValuesForKeysWithDictionary:attributes];
        [jcDic setValue:@"1" forKey:@"isBackup"];

    }else{
        [jcDic setValue:@"0" forKey:@"isBackup"];
    }
    [jcDic setValue:[NSString stringWithFormat:@"%f",fileLength] forKey:@"fileSize"];
    
    return jcDic;
    
}

/// 设定缓存路径(在下载pdf时填写的路径)
- (NSString *)jcSavePath:(NSString *)path{
    return [[self jcCachePath] stringByAppendingPathComponent:path];
}

/// 获取所有的储存pdf 文件
- (NSArray *)jcGetAllFloder{
    
    NSMutableArray *dirArray = [[NSMutableArray alloc] init];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = YES;
    BOOL isHaveFile = [fileManager fileExistsAtPath:[self jcCachePath] isDirectory:&isDir];
    if (isHaveFile) {
        NSError *error;
        NSArray *fileAndFloderArr = [fileManager contentsOfDirectoryAtPath:[self jcCachePath] error:&error];
        for (NSString * file in fileAndFloderArr){
            
            NSString *paths = [[self jcCachePath] stringByAppendingPathComponent:file];
            if ([fileManager fileExistsAtPath:paths]) {
                NSDictionary *dic = @{@"fildName":file,@"fildPath":paths};
                [dirArray addObject:dic];
            }
        }
    }
    return dirArray;
}

/// 根据路径删除储存文件
- (void)resetCacheForPath:(NSString *)paths
{
    [[NSFileManager defaultManager] removeItemAtPath:paths error:nil];
}

//======================清除缓存部分
///  获取指定缓存文件下的缓存大小
- (double)jcGetCachesWithPath:(NSString *)directory{
    
    double size = 0;
    NSFileManager *mgr = [NSFileManager defaultManager];
    BOOL isDirectory = NO;
    // 路径是否存在
    BOOL exists = [mgr fileExistsAtPath:directory isDirectory:&isDirectory];
    if (!exists) return size;
    if (isDirectory) { // 文件夹
        // 获得文件夹的大小  == 获得文件夹中所有文件的总大小
        NSDirectoryEnumerator *enumerator = [mgr enumeratorAtPath:directory];
        for (NSString *subpath in enumerator) {
            // 全路径
            NSString *fullSubpath = [directory stringByAppendingPathComponent:subpath];
            // 累加文件大小
            size += [mgr attributesOfItemAtPath:fullSubpath error:nil].fileSize;
        }
    } else { // 文件
        size = [mgr attributesOfItemAtPath:directory error:nil].fileSize;
    }
    return size/1024/1024;

}


// 清除所有缓存
- (void)jcClearCache{
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cacheDirectory = [paths objectAtIndex:0];
    NSFileManager *fileManager=[NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:cacheDirectory]) {
        
        NSArray *childerFiles=[fileManager subpathsAtPath:cacheDirectory];
        for (NSString *fileName in childerFiles) {
            //如有需要，加入条件，过滤掉不想删除的文件
//            NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
//            [fileManager removeItemAtPath:absolutePath error:nil];
            NSLog(@"---------%@",fileName);
        }
        NSLog(@"完成缓存清除");
    }
    
}






@end
